package com.yunlong.service.impl;

import com.yunlong.common.TokenInfo;
import com.yunlong.common.exception.SysException;
import com.yunlong.dto.LoginSuccessDto;
import com.yunlong.dto.MessageSuccessDto;
import com.yunlong.dto.UserInfoDto;
import com.yunlong.dto.UserPasswordDto;
import com.yunlong.entity.User;
import com.yunlong.form.*;
import com.yunlong.mapper.UserMapper;
import com.yunlong.redis.RedisRepository;
import com.yunlong.service.UserService;
import com.yunlong.exception.UserException;
import com.yunlong.util.Md5Util;
import com.yunlong.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * @author guorui
 * @date 2020-07-30 17:11
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    private final int pageSize = 5;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisRepository redisRepository;

    /**
     * 普通用户登录
     *
     * @param userLoginForm
     */
    @Override
    public LoginSuccessDto userLogin(UserLoginForm userLoginForm) {
        //密码经过md5加密处理
        String result = Md5Util.MD5Encode(userLoginForm.getUserPassword());
        User user = userMapper.selectByEmail(userLoginForm.getUserEmail());
        if (null == user) {
            log.info(userLoginForm.getUserEmail());
            log.info(result);
            log.info("用户不存在或被冻结！");
            throw new UserException("邮箱不存在！");
        } else if (!user.getUserPassword().equals(result)) {
            log.info("邮箱或密码错误");
            throw new SysException("邮箱或密码错误");
        } else {
//            判断是否异地登录
            String oldToken = redisRepository.selectLoginAccessToken(user.getUserId());
            if (null != oldToken) {
                log.info("异地登录！");
                //如果存在异地登录，删除原有的token
                redisRepository.deleteAccessToken(oldToken);
                redisRepository.deleteLoginAccessToken(user.getUserId());
            }
            //得到一个accessToken，生成tokenInfo
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setAccessToken(TokenUtil.genToken());
            tokenInfo.setUserId(user.getUserId());
            LoginSuccessDto messageSuccessLoginDto = UserServiceImpl.getMessageSuccessLoginDto(user, tokenInfo);
            //保存这个用户和token信息
            redisRepository.saveAccessToken(tokenInfo);
            redisRepository.saveLoginAccessToken(tokenInfo);
            return messageSuccessLoginDto;
        }
    }

    /**
     * 普通用户退出登录
     *
     * @param userId
     */
    @Override
    public String LoginOut(String userId) {
        User user = userMapper.selectByUserId(userId);
        if (null == user) {
            log.info("用户不存在！");
            throw new UserException("用户id不存在！");
        }
        String oldToken = redisRepository.selectUserToken(user.getUserId());
        if (null != oldToken) {
            //删除原有的token
            redisRepository.deleteAccessToken(oldToken);
            redisRepository.deleteLoginAccessToken(userId);
            return "用户退出登录成功";
        }else {
            return "用户退出登录失败";
        }
    }

    /**
     * 普通用户修改个人信息
     *
     * @param updateUserForm
     */
    @Override
    public String updateUserInfo(UpdateUserForm updateUserForm) {
        User user = userMapper.selectByUserId(updateUserForm.getUserId());
        if (null == user) {
            log.info("用户不存在！");
            throw new UserException("用户id不存在！");
        }
        userMapper.updateUserInfo(updateUserForm);
        return "修改成功";
    }

    /**
     * 忘记密码功能，查询用户的密码
     */
    @Override
    public UserPasswordDto selectUserPassword(String email) {
        return userMapper.selectUserPassword(email);
    }

    /**
     * 忘记密码之重置密码
     *
     * @param userPasswordResetForm
     */
    @Override
    public MessageSuccessDto resetPassword(UserPasswordResetForm userPasswordResetForm) {
        String userEmail = userPasswordResetForm.getUserEmail();
        String userPassword = userPasswordResetForm.getUserPassword();
        String userPassword2 = userPasswordResetForm.getUserPassword2();
        String userVerificationCode = userPasswordResetForm.getUserVerificationCode();
        String MD5Password = Md5Util.MD5Encode(userPassword);
        if(redisRepository.selectMessageCodeByEmail(userPasswordResetForm.getUserEmail())==null){
            log.info("系统未能检测到您的验证码，请稍后再试");
            throw new UserException("系统未能检测到您的验证码，请稍后再试");
        }else if(!redisRepository.selectMessageCodeByEmail(userEmail).equals(userVerificationCode)){
            log.info("验证码错误，请重新输入");
            throw new UserException("验证码错误，请重新输入");
        }else if(!userPassword.equals(userPassword2)){
            log.info("前后输入的验证码不一致，请重新输入");
            throw new UserException("前后输入的验证码不一致，请重新输入");
        }else{
            log.info("验证通过");
            //生成的id
//            userMapper.resetPassword(MD5Password);
            MessageSuccessDto registerSuccessDto = new MessageSuccessDto();
            registerSuccessDto.setMessage("重置密码成功");
            return registerSuccessDto;
        }

    }

    /**
     * 忘记密码之重置密码,系统界面
     *
     * @param updateUserPasswordInner
     */
    @Override
    public String resetPasswordInner(UpdateUserPasswordInner updateUserPasswordInner) {
        String userId = updateUserPasswordInner.getUserId();
        String userPassword = updateUserPasswordInner.getUserNewPassword();
        String userPassword2 = updateUserPasswordInner.getConfirmPassword();
        String MD5Password = Md5Util.MD5Encode(userPassword);
        if(!userPassword.equals(userPassword2)){
            log.info("前后输入的密码不一致，请重新输入");
            throw new UserException("前后输入的密码不一致，请重新输入");
        }else{
            log.info("验证通过");
            //生成的id
            userMapper.resetPassword(MD5Password,userId);
            return "重置密码成功";
        }

    }

    /**
     * 查询用户基本资料
     *
     * @param userId
     */
    @Override
    public UserInfoDto showUserInfo(String userId) {
        User user = userMapper.selectByUserId(userId);
        if (null == user) {
            log.info("用户不存在！");
            throw new UserException("用户id不存在！");
        }
        UserInfoDto userInfoDto = userMapper.selectUserInfoById(userId);
        System.out.println(userInfoDto.getStartYear());
        return userInfoDto;
    }

    /**
     * 得到普通用户登录成功返回的一个token信息
     * @param user
     * @return
     */
    public static LoginSuccessDto getMessageSuccessLoginDto(User user, TokenInfo tokenInfo){
        LoginSuccessDto messageSuccessLoginDto = new LoginSuccessDto();
        //这里看前端具体需要什么再更改吧
        messageSuccessLoginDto.setUserName(user.getUserName());
        messageSuccessLoginDto.setUserId(user.getUserId());
        messageSuccessLoginDto.setUserPhone(user.getUserEmail());
        messageSuccessLoginDto.setAccessToken(tokenInfo.getAccessToken());
        return messageSuccessLoginDto;
    }


}
